const express = require("express");
const adminServ = require("../services/adminService");
const getSendData = require("../utils/getSendData");
const parseToken = require("../utils/parseToken");
const { ValidationError } = require("../utils/errors");

const router = express.Router();

router.post("/login", async (req, res, next) => {
    const captcha = req.body.captcha.toLowerCase();
    if (req.session.captcha !== captcha) {
        throw new ValidationError("验证码错误");
    }

    const result = await adminServ.login(req.body);
    if (result.token) {
        res.setHeader("authorization", result.token);
        delete result.token;
    }
    res.send(getSendData(result.data));
});

router.get("/whoami", async (req, res, next) => {
    const token = req.headers.authorization;
    const result = parseToken(token);
    res.send(getSendData({
        id: result.id,
        loginId: result.loginId,
        name: result.name
    }));
});

router.put("/", async (req, res, next) => {
    res.send(getSendData(await adminServ.updateAdmin(req.body)));
});

module.exports = router;
